<?php

namespace App\Listeners;

use App\Events\MoneyChangeEvent;
use App\Models\Fund;
use App\Models\PointLog;
use App\Models\Stock;
use App\Models\User;
use App\Models\UserLevel;

class PointChangeListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  MoneyChangeEvent $event
     * @return void
     */
    public function handle(MoneyChangeEvent $event)
    {
        //
        $order_no = $event->order_no;
        $type = $event->type;
        if ($event->user_id > 0) {
            $user = User::whereId($event->user_id)->first();
//        dd($user);
            $buy_user = User::whereId($event->buy_user)->first();
            $level = UserLevel::whereId($user->level)->first();
            $target_id = $event->user_id;
            if ($buy_user->level > 1) {
                $target_id = $buy_user->id;
            }
            if ($type == 'fund') {
                $pvData = [6000, 10000, 12000];
                $fund = Fund::whereOrderNo($event->order_no)->first();
                $pv = $pvData[$fund->year - 1] * $fund->num;
                $insert['order_no'] = $order_no;
                $insert['point'] = $pv;
                $insert['user_id'] = $target_id;
                $point = PointLog::whereOrderNo($order_no)->first();
                if (empty($point)) {
                    $point = PointLog::create($insert);
                    $user->point = $user->point + $point->point;
                    $user->save();
                }
            } else if ($type == 'stock') {
                $stock = Stock::whereOrderNo($event->order_no)->first();
                $pv = $stock->num * 10000;
                $insert['order_no'] = $order_no;
                $insert['point'] = $pv;
                $insert['user_id'] = $target_id;
                $point = PointLog::whereOrderNo($order_no)->first();
                if (empty($point)) {
                    $point = PointLog::create($insert);
                    $user->point = $user->point + $point->point;
                    $user->save();
                }
            }
        }

    }

}
